package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityFollowUpPatientBinding
import com.compass.doctor.dialog.AppendDiagnoseDialog
import com.compass.doctor.ui.home.adapter.FollowUpPatientAdapter
import com.compass.doctor.ui.home.viewmodel.DoctorViewModel
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.visible
import com.compass.framework.manager.AppManager
import com.compass.framework.model.ScreenTag
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * Description： 随访患者
 * Date:2024/1/11 14:17
 */
class FollowUpPatientActivity : BaseVBActivity<ActivityFollowUpPatientBinding>(), OnRefreshListener,
    OnLoadMoreListener {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, FollowUpPatientActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var departmentList: ArrayList<ScreenTag> = ArrayList()
    private var positionList: ArrayList<ScreenTag> = ArrayList()

    private val doctorViewModel: DoctorViewModel by viewModels()
    private val patientViewModel: PatientViewModel by viewModels()

    private var key: String = ""
    private var type: String = "1"//1职称 2是科室
    private var mPage = 1
    private var positionId: Long? = null//职称编码
    private var departmentId: Long? = null//科室编码
    private lateinit var mAdapter: FollowUpPatientAdapter
    private lateinit var listPopupWindow: ListPopupWindow
//    private lateinit var popupAdapter: DoctorPopAdapter
    override fun initView(savedInstanceState: Bundle?) {
        initPopupWindow()
        initRecyclerView()
        mBinding.tvTitleBar.getRightLayout().onClick {
            AppendDiagnoseDialog.Builder(this).show()
        }
        mBinding.tvPositionName.onClick {
            type = "1"
            listPopupWindow.anchorView = mBinding.tvPositionName
//            popupAdapter.setList(positionList)
            listPopupWindow.show()
        }
        mBinding.spDepartments.onClick {
            type = "2"
            listPopupWindow.anchorView = mBinding.spDepartments
//            popupAdapter.setList(departmentList)
            listPopupWindow.show()
        }
        mBinding.edtDiagnosis.textChangeFlow()
            .distinctUntilChanged()
            .debounce(500)
            .flowOn(Dispatchers.IO)
            .onEach {
                //这里走查询接口
                key = mBinding.edtDiagnosis.text.toString().trim()
                getPatientList()
            }
            .launchIn(lifecycleScope)

    }


    override fun intListener() {
        listPopupWindow.setOnItemClickListener { parent, view, position, id ->

        }
    }

    private fun initPopupWindow() {
        listPopupWindow = ListPopupWindow(this)
//        popupAdapter = DoctorPopAdapter(this)
//        listPopupWindow.setAdapter(popupAdapter)
        listPopupWindow.width = (AppManager.getScreenWidthPx() * 0.3).toInt()
        listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        val bgDrawable = ContextCompat.getDrawable(
            this,
            R.drawable.ps_permission_desc_bg
        )
        listPopupWindow.setBackgroundDrawable(bgDrawable)
        listPopupWindow.isModal = true
//        popupAdapter.setOnCustomItemClick(object : OnCustomItemClick {
//            override fun onItemCallBack(position: Int, value: String, label: String) {
//                if (type == "1") {
//                    positionId = positionList[position].id
//                    mBinding.tvPositionName.text = positionList[position].name
//                } else {
//                    departmentId = departmentList[position].id
//                    mBinding.spDepartments.text = departmentList[position].name
//                }
//                listPopupWindow.dismiss()
//                getPatientList()
//            }
//        })
    }

    override fun initData() {
        doctorViewModel.getPositionList()
        doctorViewModel.getDepartmentList()
        getPatientList()
        patientViewModel.patientListLiveData.observe(this){
            dismissLoading()
            if (mPage == 1) {
                mAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
                } else {
                    mBinding.emptyView.gone()
                }
            } else {
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }
        }
        doctorViewModel.departmentLiveData.observe(this) {
            departmentList = it as ArrayList<ScreenTag>
        }
        doctorViewModel.positionLiveData.observe(this) {
            positionList = it as ArrayList<ScreenTag>
        }

    }

    /**
     * 获取推荐列表数据
     */
    private fun getPatientList() {
        showLoading()
        patientViewModel.getPatientList(1, key = key)
    }



    private fun initRecyclerView() {
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@FollowUpPatientActivity)
            setOnLoadMoreListener(this@FollowUpPatientActivity)
        }
        mAdapter = FollowUpPatientAdapter()
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
        mAdapter.onItemClickListener = { _: View, position: Int ->
            val doctor = mAdapter.getItem(position)
            doctor?.let {
                FollowUpDetailsActivity.start(this)
            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getPatientList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getPatientList()
    }
}